package com.siruier.boss.ui.activity.mall

import android.Manifest
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapsInitializer
import com.amap.api.maps.model.MyLocationStyle
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.poisearch.PoiSearch
import com.siruier.boss.R
import com.siruier.boss.api.core.launchUI
import com.siruier.boss.bean.LocationSelect
import com.siruier.boss.databinding.ActivityLocationSelectBinding
import com.siruier.boss.databinding.ItemLocBinding
import com.siruier.boss.ui.api.ApiObserver
import com.siruier.boss.ui.base.BaseActivity
import com.siruier.boss.ui.base.BaseRecyclerAdapter
import com.siruier.boss.ui.bean.picker.BaseCityBean
import com.siruier.boss.ui.ext.permissionRequest
import com.siruier.boss.ui.ext.toColor
import com.siruier.boss.ui.ext.toastMessageLong
import com.siruier.boss.ui.helper.LocationHelper.initLocation
import com.siruier.boss.ui.helper.LocationHelper.loadMapLocation
import com.siruier.boss.ui.utils.Logger
import com.zaaach.citypicker.CityPicker
import com.zaaach.citypicker.adapter.OnPickListener
import com.zaaach.citypicker.model.City
import com.zaaach.citypicker.model.HotCity
import com.zaaach.citypicker.model.LocatedCity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext


class LocationSelectActivity : BaseActivity<ActivityLocationSelectBinding>() {

    private var mLocAdapter: LocAdapter? = null
    private var mCityBean: BaseCityBean? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        permissionRequest {
            permission(Manifest.permission.ACCESS_COARSE_LOCATION)
            permission(Manifest.permission.ACCESS_FINE_LOCATION)
            permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            permission(Manifest.permission.READ_EXTERNAL_STORAGE)
            permission(Manifest.permission.READ_PHONE_STATE)
            onGranted {
                initLocation()
                initMapView(savedInstanceState)
            }
            onDenied {
                "权限拒绝无法定位".toastMessageLong()
            }
        }
    }

    override fun onClick(v: View?) {
        when (v) {
            vb.searchView -> launchStartActivityForResult(LocationSearchActivity::class.java, options = {
                Logger.e("===${mCityBean?.code}")
                putString("cityCode", mCityBean?.code)
            }) {
                setResult(RESULT_OK, it.data)
                finish()
            }
            vb.flCity -> {
                val mHotCities = mutableListOf<HotCity>()
                mHotCities.add(HotCity("北京", "北京", "110100"))
                mHotCities.add(HotCity("上海", "上海", "310100"))
                mHotCities.add(HotCity("广州", "广东", "440100"))
                mHotCities.add(HotCity("深圳", "广东", "440300"))
                mHotCities.add(HotCity("天津", "天津", "120100"))
                mHotCities.add(HotCity("杭州", "浙江", "330100"))
                mHotCities.add(HotCity("南京", "江苏", "320100"))
                mHotCities.add(HotCity("成都", "四川", "510100"))
                mHotCities.add(HotCity("武汉", "湖北", "420100"))
                CityPicker.from(mThis)
                    .enableAnimation(true)
                    .setHotCities(mHotCities)
                    .setAnimationStyle(R.style.DefaultCityPickerAnimation)
                    .apply {
                        if (mCityBean != null) {
                            setLocatedCity(LocatedCity(mCityBean?.name, mCityBean?.name, mCityBean?.code))
                        }
                    }
                    .setOnPickListener(object : OnPickListener {
                        override fun onPick(position: Int, data: City) {
                            mCityBean = BaseCityBean(data.code, data.name)
                            vb.tvCity.text = data.name
                        }

                        override fun onCancel() {

                        }

                        override fun onLocate() {

                        }
                    })
                    .show()
            }
        }
    }

    private fun initMapView(savedInstanceState: Bundle?) {
        MapsInitializer.updatePrivacyShow(application, true, true)
        MapsInitializer.updatePrivacyAgree(application, true)
        vb.mapView.onCreate(savedInstanceState)
        val aMap = vb.mapView.map
        setUpMap(aMap)
        launchUI({
            loadMapLocation()?.let { ml ->
                val locationSelect = LocationSelect(
                    BaseCityBean("${ml.adCode.substring(0, 2)}0000", ml.province),
                    BaseCityBean("${ml.adCode.substring(0, 4)}00", ml.city).also {
                        mCityBean = it
                        vb.tvCity.text = ml.city
                    },
                    BaseCityBean(ml.adCode, ml.district),
                    ml.poiName, ml.poiName, ml.address
                )
                val poiSearchQuery = PoiSearch.Query(null, null, ml.cityCode)
                poiSearchQuery.pageSize = 20
                poiSearchQuery.pageNum = 1
                val poiSearch = PoiSearch(application, poiSearchQuery)
                poiSearch.bound = PoiSearch.SearchBound(LatLonPoint(ml.latitude, ml.longitude), 1000)
                val poiResult = withContext(Dispatchers.IO) { poiSearch.searchPOI() }
                val datas = poiResult.pois.mapTo(mutableListOf()) { pt ->
                    LocationSelect(
                        BaseCityBean("${ml.adCode.substring(0, 2)}0000", pt.provinceName),
                        BaseCityBean("${ml.adCode.substring(0, 4)}00", pt.cityName),
                        BaseCityBean(ml.adCode, pt.adName),
                        pt.title, pt.snippet, pt.provinceName + pt.cityName + pt.adName + pt.snippet
                    )
                }
                datas.add(0, locationSelect)
                vb.rvDot.layoutManager = LinearLayoutManager(applicationContext)
                mLocAdapter = LocAdapter(datas)
                vb.rvDot.adapter = mLocAdapter
                mLocAdapter?.setOnClickAdapterListenter { view, i ->
                    setResult(RESULT_OK, Intent().apply {
                        putExtra("locationSelect", mLocAdapter?.getItem(i))
                    })
                    finish()
                }
                bindViewClick(vb.flCity, vb.searchView)
            }
        }, ApiObserver())
    }

    class LocAdapter(datas: MutableList<LocationSelect>) : BaseRecyclerAdapter<ItemLocBinding, LocationSelect>(datas) {

        override fun onBindViewHolder(vb: ItemLocBinding, bean: LocationSelect, position: Int) {
            vb.ivLoc.setImageResource(
                if (position == 0) {
                    R.mipmap.icon_loc
                } else {
                    R.mipmap.icon_un_loc
                }
            )
            vb.tvTitle.setTextColor(
                if (position == 0) {
                    R.color.mall_main.toColor()
                } else {
                    R.color.text_color.toColor()
                }
            )
            vb.tvTitle.text = bean.title
            vb.tvAddress.text = bean.address
            setViewClick(position, vb.root)
        }
    }

    /**
     * 设置一些amap的属性
     */
    private fun setUpMap(aMap: AMap) {
        // 设置默认定位按钮是否显示
        aMap.uiSettings.apply {
            isMyLocationButtonEnabled = false
            isZoomControlsEnabled = false
        }
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16f))
        // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.isMyLocationEnabled = true
        setupLocationStyle(aMap)
    }

    /**
     * 设置自定义定位蓝点
     */
    private fun setupLocationStyle(aMap: AMap) {
        // 自定义系统定位蓝点
        val myLocationStyle = MyLocationStyle()
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE)
//        //自定义精度范围的圆形边框宽度
        myLocationStyle.strokeWidth(0f)
//        // 设置圆形的填充颜色
        myLocationStyle.radiusFillColor(Color.TRANSPARENT)
        // 将自定义的 myLocationStyle 对象添加到地图上
        aMap.myLocationStyle = myLocationStyle
    }

    override fun onResume() {
        super.onResume()
        vb.mapView.onResume()
    }

    /**
     * 方法必须重写
     */
    override fun onPause() {
        super.onPause()
        vb.mapView.onPause()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        vb.mapView.onSaveInstanceState(outState)
    }

    /**
     * 方法必须重写
     */
    override fun onDestroy() {
        super.onDestroy()
        vb.mapView.onDestroy()
    }
}